<?php

namespace app\models;

use app\models\warehouse\OrderCartInfo;
use think\facade\Cache;
use think\facade\Db;
use think\Model;


class Order extends Model
{

    protected $table = 'xd_store_order';

    public function OrderCartInfo()
    {
        //点赞记录
        return $this->hasMany(OrderCartInfo::class,'oid', 'id');
    }

    /**
     * 雪花算法生成订单id
     * @param string $prefix
     * @return string
     * @throws \Exception
     */
    public function getNewOrderId(string $prefix = 'wx')
    {

        $snowflake = new \Godruoyi\Snowflake\Snowflake();
        $is_callable = function ($currentTime) {
            $redis = Cache::store('redis');
            $swooleSequenceResolver = new \Godruoyi\Snowflake\RedisSequenceResolver($redis->handler());
            return $swooleSequenceResolver->sequence($currentTime);
        };
        //32位
        if (PHP_INT_SIZE == 4) {
            $id = abs($snowflake->setSequenceResolver($is_callable)->id());
        } else {
            $id = $snowflake->setStartTimeStamp(strtotime('2020-06-05') * 1000)->setSequenceResolver($is_callable)->id();
        }
        return $prefix . $id;
    }


    /**
     * 获取购物车商品详情
     * @return void
     */
    public function getgoodDeilt($id){


        $data = Db::table('xd_store_product')->where('id',$id)->where('is_show','1')->find();

        $data['resurt'] = Db::table('xd_store_product_attr_result')->where('product_id',$id)->find();
        $data['value'] = Db::table('xd_store_product_attr_value')->where('product_id',$id)->find();
        $data['description'] = Db::table('xd_store_product_description')->where('product_id',$id)->find();

        return $data;
    }




    public function getCartData($cartId){

        $data = Db::table('xd_store_cart')
                ->alias('c')
                ->field('c.cart_num,p.price')
                ->whereIn('c.id',$cartId)
                ->leftjoin(['xd_store_product'=>'p'] ,'p.id=c.product_id')
                ->select();

        if(!empty($data)){

            $price = 0;
            $num = 0;
            foreach($data as $k=>$v){
                $price =$price + $v['cart_num']*$v['price'];
                $num  =$num + $v['cart_num'];
            }
            $res = [
                'price'=>$price,
                'num'=>$num
            ];
        }else{
            $res = [
                'price'=>0,
                'num'=>0
            ];
        }
        return $res;
    }
}
